/******************************************************************************
** 
** Integer to strings.
** 
** File name:	itoa.c
** Compilation:	cc -g itoa.c -o itoa
** Execution:	./itoa
** 
** Description:
** Converts a decimal number to the corresponding string. Let's pretend that 
** printf("%d") is forbidden.
** 
******************************************************************************/
#include <stdio.h>
#include "myfunctions.h"

#define MAX_STR_LEN 255

void IToA (int n, char s[]);
void ReverseString(char s[]);

int main()
{
    int n;
    char str[MAX_STR_LEN];
    
    n = -34567;
    IToA(n, str);
    printf("%s\n", str);
    
    
    return 0;
}


// IToA: Converts a integer digits to the corresponding sequence of chars.
void IToA (int n, char s[]) {
    unsigned short int i;
    int sign;

    if ((sign = n) < 0) {
        n = -n;
    }

    i = 0;
    do {
        s[i++] = n % 10 + '0';
    } while ((n /= 10) > 0);

    if (sign < 0) {
        s[i++] = '-';
    }
    s[i] = ENDLINE_SYMBOL;

    ReverseString(s);
}

// ReverseString: Reverses the string.
void ReverseString(char s[]) {
    unsigned short int i;
    unsigned short int length;
    char tmp;
    
    length = 0;
    while (s[length] != ENDLINE_SYMBOL) {
        length++;
    }
    length--;
    
    i = 0;
    while (i < length) {
        tmp = s[i];
        s[i] = s[length];
        s[length] = tmp;
        i++;
        length--;
    }    
}
